package org.osami.gateway.watteco;

import java.io.IOException;
import java.util.logging.Logger;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;
import org.osami.gateway.watteco.interfaces.IW1NodeIPv4;

@Component
@Instantiate
public class DiscoveryIPv4 extends Thread
{
    private static final Logger logger = Logger.getLogger(DiscoveryIPv4.class.getName());

    @Requires
    private IW1NodeIPv4 controller;

    private volatile static boolean quit;
    private final long delay = 1500;
    private final long dutyCycle = 8;
    private static int thread = 0;

    public DiscoveryIPv4() {

    }

    // TODO MAYBE: periodically retrieve the list of serial ports, and dynamically query them with "?" + "$SN;" to discover W1 items ?
    // (in which case we need a Device/Driver pair for W1Node as well).
    // But does it make much sense to connect multiple W1 devices of the same type to the gateway ?
    public void run() {
        if (DiscoveryIPv4.thread == 0) {
            logger.finer("Thread 1");
            try
            {
                controller.sendFullReset();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        else {
            logger.finer("Thread 2");
            try {
                Thread.sleep(15000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            int i = 0;
            while (!quit)
            {
                if (i % dutyCycle == 0)
                {
                    i = 0;
                    try {
                        controller.discoverSmartplugs();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }

                try
                {
                    Thread.sleep(this.delay);
                }
                catch (InterruptedException e)
                {
                }
                logger.fine("DiscoveryIPv4 waking up " + i);
                i++;
            }
        }
    }

    @Validate
    private void startup()
    {
        logger.info("===== Starting Watteco smartplugs DiscoveryIPv4 =====");
        this.quit = false;

        try {
            thread = 0;
            new Thread(this).start();
            Thread.sleep(100);
            thread = 1;
            new Thread(this).start();
            Thread.sleep(100);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Invalidate
    private void shutdown()
    {
        logger.info("===== Stopping Watteco smartplugs DiscoveryIPv4 =====");
        this.quit = true;
    }
}
